<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标准名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入标准名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId">
        <div style="width: 194px; display: inline; float: left">
          <treeselect
            v-model="queryParams.deptId"
            :options="deptOptions"
            :show-count="true"
            :clearable="false"
            placeholder="请选择所属部门"
            :normalizer="normalizer"
          />
        </div>
      </el-form-item>
      <el-form-item label="适用设备" prop="equipmentIds">
        <el-select v-model="queryParams.equipmentIds" placeholder="请选择适用设备" clearable size="small">
          <el-option
            v-for="item in equipmentOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="使用类别" prop="typeIds">
        <div style="width: 194px; display: inline; float: left">
          <treeselect
            v-model="queryParams.typeIds"
            :options="eqTypeOptions"
            :show-count="true"
            :clearable="false"
            placeholder="请选择设备类别"
            :normalizer="normalizer"
          />
        </div>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)"
                       :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['ems:maintain-standard:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['ems:maintain-standard:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list" :cell-class-name="cellClassName" @row-click="handleCellClick">
      <el-table-column label="保养标准id" align="center" prop="id" />
      <el-table-column label="标准名称" align="center" prop="name" />
      <el-table-column label="所属部门" align="center" prop="deptId" :formatter="deptNameFormat" />
      <el-table-column label="标准说明" align="center" prop="remarks" />
      <el-table-column label="适用设备" align="center" prop="equipmentIds">
        <template slot-scope="scope">
          <el-tag :disable-transitions="true" :key="index" v-for="(equipment, index) in scope.row.equipmentIds" :index="index">
            {{ eqNameFormat(equipment) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用类别" align="center" prop="typeIds" >
        <template slot-scope="scope">
          <el-tag :disable-transitions="true" :key="index" v-for="(type, index) in scope.row.typeIds" :index="index">
            {{ typeNameFormat(type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['ems:maintain-standard:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['ems:maintain-standard:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="740px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标准名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入标准名称" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :show-count="true"
                :clearable="false"
                placeholder="请选择所属部门"
                :normalizer="normalizer"
              />
        </el-form-item>
        <el-form-item label="标准说明" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入标准说明" type="textarea"/>
        </el-form-item>
        <el-form-item label="适用设备" prop="equipmentIds">
          <el-select v-model="form.equipmentIds" placeholder="请选择适用设备" multiple collapse-tags>
            <el-option
              v-for="item in equipmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用类别" prop="typeIds">
          <div style="width: 194px; display: inline; float: left">
            <treeselect
              v-model="form.typeIds"
              :multiple="true" 
              :options="eqTypeOptions"
              :show-count="true"
              :clearable="false"
              placeholder="请选择设备类别"
              :normalizer="normalizer"
            />
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)"
                       :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <el-card shadow="hover" class="box-card">
          <div slot="header" class="clearfix">
            <span>保养项目</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              icon="el-icon-circle-plus-outline"
              v-hasPermi="['ems:maintain-standard:update']"
              @click="addItem()"
              >新增</el-button
            >
          </div>
          <el-form-item
            label-width="0"
            v-for="(item, index) in form.maintainStandardItem"
            :key="index"
          >
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item
                  label="模块"
                  :prop="'maintainStandardItem.' + index + '.module'"
                  :rules="{required: true, message: '模块不能为空', trigger: 'blur'}"
                >
                  <el-input v-model="item.module" placeholder="请输入模块" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="编号"
                  :prop="'maintainStandardItem.' + index + '.number'"
                >
                  <el-input v-model="item.number" placeholder="请输入编号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="保养类型"
                  :prop="'maintainStandardItem.' + index + '.maintainType'"
                >
                  <el-select v-model="item.maintainType" placeholder="请选择保养类型">
                    <el-option v-for="dict in maintainTypeDictDatas"
                              :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item
                  label="项目"
                  :prop="'maintainStandardItem.' + index + '.program'"
                >
                  <el-input v-model="item.program" placeholder="请输入项目" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item
                  label="内容"
                  :prop="'maintainStandardItem.' + index + '.content'"
                >
                  <el-input v-model="item.content" placeholder="请输入内容" type="textarea"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label="类型"
                  :prop="'maintainStandardItem.' + index + '.type'"
                >
                  <el-select v-model="item.type" placeholder="请选择类型">
                    <el-option v-for="dict in typeDictDatas"
                              :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="上限"
                  :prop="'maintainStandardItem.' + index + '.upperLimit'"
                >
                  <el-input v-model="item.upperLimit" placeholder="请输入上限"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="下限"
                  :prop="'maintainStandardItem.' + index + '.lowerLimit'"
                >
                  <el-input v-model="item.lowerLimit" placeholder="请输入下限"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label="可选项"
                  :prop="'maintainStandardItem.' + index + '.options'"
                >
                  <el-input v-model="item.options" placeholder="请输入可选项"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="正常选项"
                  :prop="'maintainStandardItem.' + index + '.normalOptions'"
                >
                  <el-input v-model="item.normalOptions" placeholder="请输入正常选项"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row type="flex" justify="end">
              <el-col :span="3">
                <el-button
                  icon="el-icon-plus"
                  v-hasPermi="['ems:maintain-standard:update']"
                  @click="addItem()"
                  circle
                ></el-button>
                <el-button
                  icon="el-icon-delete"
                  v-hasPermi="['ems:maintain-standard:update']"
                  @click.prevent="removeInfo(item)"
                  circle
                ></el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看详细 -->
    <el-dialog title="保养标准信息" :visible.sync="dialog" width="740px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="标准名称" prop="name">
          {{form.name}}
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          {{ deptNameFormat2(form.deptId) }}
        </el-form-item>
        <el-form-item label="标准说明" prop="remarks">
          {{form.remarks}}
        </el-form-item>
        <el-form-item label="适用设备" prop="equipmentIds">
          <el-tag :disable-transitions="true" :key="index" v-for="(equipment, index) in form.equipmentIds" :index="index">
            {{ eqNameFormat(equipment) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="使用类别" prop="typeIds">
          <el-tag :disable-transitions="true" :key="index" v-for="(equipment, index) in form.typeIds" :index="index">
            {{ typeNameFormat(equipment) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="form.status" />
        </el-form-item>
        <el-card shadow="hover" class="box-card">
          <div slot="header" class="clearfix">
            <span>保养项目</span>
          </div>
          <el-form-item
            label-width="0"
            v-for="(item, index) in form.maintainStandardItem"
            :key="index"
          >
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item
                  label="模块"
                  :prop="'maintainStandardItem.' + index + '.module'"
                  :rules="{required: true, message: '模块不能为空', trigger: 'blur'}"
                >
                  {{item.module}}
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="编号"
                  :prop="'maintainStandardItem.' + index + '.number'"
                >
                  {{item.number}}
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="保养类型"
                  :prop="'maintainStandardItem.' + index + '.maintainType'"
                >
                  <dict-tag :type="DICT_TYPE.COMMON_TIME_TYPE" :value="item.maintainType" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item
                  label="项目"
                  :prop="'maintainStandardItem.' + index + '.program'"
                >
                  {{item.program}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item
                  label="内容"
                  :prop="'maintainStandardItem.' + index + '.content'"
                >
                  {{item.content}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label="类型"
                  :prop="'maintainStandardItem.' + index + '.type'"
                >
                  <dict-tag :type="DICT_TYPE.EMS_MAINTAINSTANDARD_ITEM_TYPE" :value="item.type" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="上限"
                  :prop="'maintainStandardItem.' + index + '.upperLimit'"
                >
                  {{item.upperLimit}}
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="下限"
                  :prop="'maintainStandardItem.' + index + '.lowerLimit'"
                >
                  {{item.lowerLimit}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label="可选项"
                  :prop="'maintainStandardItem.' + index + '.options'"
                >
                  {{item.options}}
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="正常选项"
                  :prop="'maintainStandardItem.' + index + '.normalOptions'"
                >
                  {{item.normalOptions}}
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </el-card>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { createMaintainStandard, updateMaintainStandard, deleteMaintainStandard, getMaintainStandard, getMaintainStandardPage, exportMaintainStandardExcel, deleteInfo } from "@/api/ems/maintainStandard";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listSimpleDepts, listDept } from "@/api/system/dept";
import { listSimpleEqTypes } from "@/api/ems/eqType";
import { listSimpleEquipments } from "@/api/ems/equipment";
import {DICT_TYPE, getDictDatas} from "@/utils/dict";

export default {
  name: "MaintainStandard",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 保养标准列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        name: null,
        deptId: null,
        equipmentIds: null,
        typeIds: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        status: [{ required: true, message: "状态不能为空", trigger: "change" }],
      },
      depts: [],
      equipments: [],
      eqTypeOptions: undefined,
      deptOptions: [],
      equipmentOptions: [],
      transferProps: {
        key: "id",
        label: "name",
      },
      // 数据字典
      maintainTypeDictDatas: getDictDatas(DICT_TYPE.COMMON_TIME_TYPE),
      typeDictDatas: getDictDatas(DICT_TYPE.EMS_MAINTAINSTANDARD_ITEM_TYPE),
      dialog: false
    };
  },
  created() {
    this.getList();
    listDept().then((response) => {
      this.depts = response.data;
    });
    this.getTreeselect();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getMaintainStandardPage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        deptId: undefined,
        remarks: undefined,
        equipmentIds: undefined,
        typeIds: undefined,
        status: undefined,
        maintainStandardItem: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加保养标准";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getMaintainStandard(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改保养标准";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateMaintainStandard(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createMaintainStandard(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除保养标准编号为"' + id + '"的数据项?').then(function() {
          return deleteMaintainStandard(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm('是否确认导出所有保养标准数据项?').then(() => {
          this.exportLoading = true;
          return exportMaintainStandardExcel(params);
        }).then(response => {
          this.$download.excel(response, '保养标准.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },
    /** 查询类别下拉树结构 + 岗位下拉 */
    getTreeselect() {
      listSimpleEqTypes().then((response) => {
        // 处理 storeOptions 参数
        this.eqTypeOptions = [];
        this.eqTypeOptions.push(...this.handleTree(response.data, "id"));
      });
      listSimpleDepts().then((response) => {
        this.deptOptions.push(...this.handleTree(response.data, "id"));
      });
      listSimpleEquipments().then((response) => {
        this.equipmentOptions = response.data;
      });
    },
    // 格式化分类的下拉框
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    getDept(data) {
      for (const dept of this.depts) {
        if (data === dept.id) {
          return dept.name;
        }
      }
    },
    // 部门展示
    deptNameFormat(row, column) {
      if (!row.deptId) {
        return "未设置";
      }
      for (const dept of this.depts) {
        if (row.deptId === dept.id) {
          return dept.name;
        }
      }
      return "未知【" + row.deptId + "】";
    },
    deptNameFormat2(deptId) {
      if (!deptId) {
        return "未设置";
      }
      for (const dept of this.depts) {
        if (deptId === dept.id) {
          return dept.name;
        }
      }
      return "未知【" + deptId + "】";
    },
    eqNameFormat(equipment) {
      if (!equipment) {
        return "未设置";
      }
      for(const eq of this.equipmentOptions) {
        if (equipment === eq.id) {
          return eq.name;
        }
      }
      return "未知【" + equipment + "】";
    },
    typeNameFormat(type) {
      if (type === undefined) {
        return "未设置";
      }
      for(const eq of this.eqTypeOptions) {
        if (type === eq.id) {
          return eq.name;
        }
      }
      return "未知【" + type + "】";
    },
    // 添加内容
    addItem() {
      this.form.maintainStandardItem.push({
        content: "",
        id: null,
        maintainType: null,
        module: "",
        number: "",
        program: "",
        standardId: null,
        type: null,
        upperLimit: "",
        lowerLimit: "",
        options: "",
        normalOptions: "",
        remarks: "",
      });
    },
    removeInfo(item) {
      let index = this.form.maintainStandardItem.indexOf(item);
      if (index !== -1) {
        this.form.maintainStandardItem.splice(index, 1);
        if (item.standardId !== null) {
          this.$confirm("确认要删除当保养项目吗?", "警告", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(async () => {
              await deleteInfo(item.id);
              // this.getSupplierList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            })
            .catch((err) => {
              console.error(err);
            });
        }
      }
    },
    // 先利用单元格的className方法，给行列索引赋值
    cellClassName({row, column, rowIndex, columnIndex}){
      row.index = rowIndex;
      column.index = columnIndex;
    },
    handleCellClick(row, column, cell, event) {
      console.log(column.index)
	    if(column.index !== 8) {
        this.reset();
        const id = row.id;
        getMaintainStandard(id).then(response => {
          this.form = response.data;
          this.dialog = true;
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
  .el-row {
    margin-bottom: 10px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-form-item{
    margin-bottom: 30px;
    &:last-child {
      margin-bottom: 0;
    }
  }
</style>